package zcj.stu.service;

import cn.hutool.core.util.StrUtil;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import zcj.stu.Entity.Order;
import zcj.stu.dao.CommonDao;
import zcj.stu.utils.Result;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class CommonService {
    @Resource
    private CommonDao commonDao;
    public Result getAccountPage(int currentPage, int pageSize, Class classs, String search) {
        long count = commonDao.getTotalCount(classs);
        int totalPage = (int) ( (count/ pageSize) + (count % pageSize>0?1:0));
        if (currentPage > totalPage) {
            currentPage = totalPage;
        }
        int skip = (currentPage - 1) * pageSize;
        int limit = pageSize;

        Criteria criteria = new Criteria("_id").exists(true);
        if(StrUtil.isNotBlank(search)){
            System.out.println(search);
            if(search.contains("$")){
                search = search.substring(0,search.length()-1);
                System.out.println(search+"....");
                criteria.orOperator(Criteria.where("_id").is(search));
            }else {
                Pattern pattern = Pattern.compile("^.*" + search + ".*$", Pattern.CASE_INSENSITIVE);

                criteria.orOperator(Criteria.where("name").regex(pattern)
                        ,Criteria.where("price").regex(pattern)
                        , Criteria.where("num").regex(pattern)
                        , Criteria.where("isSale").regex(pattern)
                        , Criteria.where("category").regex(pattern)
                );
            }
        }
        Query query = Query.query(criteria);
        if(classs==Order.class){
            Sort.Order order =new Sort.Order(Sort.Direction.DESC, "order_add_time");
            query.with(Sort.by(order));
        }
        query.skip(skip).limit(limit);
        List datas = commonDao.queryPage(query,classs);
        Result result = new Result();
        result.setData(datas);
        result.put("total",count);
        return result;
    }
}
